package com.ruoyi.feike.controller;


//import com.deepoove.poi.XWPFTemplate;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.feike.domain.BasicInformation;
import com.ruoyi.feike.domain.DealercodeCount;
import com.ruoyi.feike.service.IBasicInformationService;
import com.ruoyi.feike.service.IDealercodeCountService;
import com.sun.xml.internal.bind.v2.TODO;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
//import java.util.HashMap;
//import java.util.Map;




import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
//import java.io.FileOutputStream;
//import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/api/fileWork")
//TODO: 作为产品标准功能, 迁移到web-api-service
public class PdfController {
    @Autowired
    private IBasicInformationService basicInformationService;
    @Autowired
    private IDealercodeCountService dealercodeCountService;

//    @PostMapping("/toPdf")
//    public void generatePdf(@RequestBody Map parameters, HttpServletResponse response) {
//        //String contractlocation =(String)parameters.get("contractlocation");
//        try {
//            //word文件放这里
//            //你既然前端传地址参数   就不用写死   写参数就行
//            FileInputStream fileInputStream = new FileInputStream(this.getClass().getClassLoader().getResource("").getPath()+parameters.get("contractlocation").toString());
//            XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
//            PdfOptions pdfOptions = PdfOptions.create();
//            //转为PDF之后放到这里
//            FileOutputStream fileOutputStream = new FileOutputStream("D:\\testPdf\\poi笔记.pdf");
//            PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
//            fileInputStream.close();
//            fileOutputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        response.setContentType("application/pdf");
//        FileInputStream in;
//        OutputStream out;
//        try {
//            //PDF文件转为流这个pdf文件还会存起来？？我服务器上没位置给他存啊
//            //可以吧路径改到项目相对路径，就是存项目里
//            //先试试本地
//            in = new FileInputStream(new File("D:\\testPdf\\poi笔记.pdf"));
//            out = response.getOutputStream();
//            byte[] b = new byte[512];
//            while ((in.read(b)) != -1) {
//                out.write(b);
//                out.flush();
//            }
//            //返回给前端了就删项目里的
//            new File("F:\\poi笔记.pdf").delete();
//            in.close();
//            out.close();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    @PostMapping("/toWord")
    public void generateWord(@RequestBody Map parameters, HttpServletResponse response) {
        try {
//            String parameters="af359e97cb424cd0a0c3409ae61c2baf";
//            String[] params = parameters.split(",");
//            String[] params = {"af359e97cb424cd0a0c3409ae61c2baf"};
//            String contractId = "fe7da17113264ecfa640dd69b699667d";
            System.out.println("合同下载成功");
            String contractlocation =(String)parameters.get("contractlocation");
            String contractname =(String)parameters.get("contractname");

            String dealerNameCN =(String)parameters.get("dealerNameCN");
            String sector =(String)parameters.get("sector");
            String instanceId =(String)parameters.get("instanceId");
            //调用方法通过传的参数获取到该合同的dealercode
            String dealercode = dealercodelist(instanceId, dealerNameCN, sector);

            Map<String, Object> data = new HashMap<>();
            //根据不同的合同插入不同的合同号
            if(contractname.equals("人民币循环贷款合同")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"F");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("浮动抵押")){
                //同一个Dealer Code项下，M后的信息与主合同F后的相同
//                DealercodeCount dealercodeCount2 = new DealercodeCount();
//                dealercodeCount2.setTemp("F");
//                dealercodeCount2.setDealercode(dealercode);
//                List<DealercodeCount> dealercodeCounts1 = dealercodeCountService.selectDealercodeCountList(dealercodeCount2);
//                if(StringUtils.isNotEmpty(dealercodeCounts1)){
//                    Long count = dealercodeCounts1.get(0).getCount();
//                }
                String maincontractno = maincontractno(dealercode,"M");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("三方")||contractname.equals("三方-C")||contractname.equals("三方-E")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"W");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("主信托")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"T");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("个人保函")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"G");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("企业保函")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"C");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("试乘试驾车贷款合同")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"DEMO");
                data.put("contract",maincontractno);
            }
            if(contractname.equals("试驾车个人保函")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"DEMO");
                data.put("contract",maincontractno+"-G");
            }
            if(contractname.equals("试驾车企业保函")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"DEMO");
                data.put("contract",maincontractno+"-C");
            }
            if(contractname.equals("DEMO抵押合同")){
                //调用方法拼出主合同号
                String maincontractno = maincontractno(dealercode,"DEMO");
                data.put("contract",maincontractno+"-M");
            }


            data.put("groupGuarantee","测试");
            data.put("name",contractname);
//            String path = this.getClass().getClassLoader().getResource("").getPath();
//            String a = RuoYiConfig.getProfile() + contractlocation.substring(8);
            XWPFTemplate template = XWPFTemplate.compile("/"+RuoYiConfig.getProfile() + contractlocation.substring(8))
                    .render(data);
            OutputStream out;
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(String.valueOf(contractname)+".docx","utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
//            out= response.getOutputStream();
             out = new FileOutputStream("D:\\下载\\"+contractname+".docx");
            template.write(out);
            out.flush();
            out.close();
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @GetMapping("/toWords")
        public  void toWords() throws IOException {
            //1.在java中创建一个保存数据的map，key为对应word文本中的标签，值为要替换的数据，会将map中的对应的key替换为value
            Map<String, Object> datas = new HashMap<String, Object>();
            //2.给map添加要替换的数据
            //(1)简单的数据，替换的文本数据
            datas.put("groupGuarantee", "数据内容");//可直接添加到map中
            //(2)动态的表格列表数据，要创建List集合，数据类型为map类型，map中的key为word中要遍历的列，值为要替换的内容
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//创建map的List集合
            for (int i = 0; i < 6; i++) {    //用循环添加每行的数据，添加6行数据
                Map<String, Object> detailMap = new HashMap<String, Object>();//将word中标签名的例和对应数据保存到map
                detailMap.put("index", i + 1);//序号
                detailMap.put("title", "商品" + i);//商品名称
                detailMap.put("product_description", "套");//商品规格
                detailMap.put("buy_num", 3 + i);//销售数量
                detailMap.put("saleprice", 100 + i);//销售价格
                list.add(detailMap);//将设置好的行保存到list集合中
            }
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();//创建一个列表的规则
            Configure config = Configure.newBuilder().bind("list", policy).build();//设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
//            datas.put("list", list);        //将列表保存到渲染的map中
            //3.创建XWPFTemplate对象，并设置读取模板路径和要渲染的数据
            XWPFTemplate template = XWPFTemplate.compile(this.getClass().getClassLoader().getResource("").getPath() + "/template/二手车业务-最高额保证担保合同（清洁稿）.docx", config).render(datas);
            //compile(模板路径,对应的配置)方法是设置模板路径和模板配置的，如果不设置配置时可不传config
            //render(datas)方法是用来渲染数据，将准备好的map数据方进去渲染
            //4.模板的输出，用FileOutputStream输出流（可以输出到指定文件位置，也可以用ajax直接返回给浏览器下载）
            FileOutputStream out = new FileOutputStream("D:/out/1.docx");//创建文件输出流并指定位置
            template.write(out);    //用XWPFTemplate对象的写write()方法将流写入
        }

//    public void generateWords(@RequestBody Map parameters, HttpServletResponse response) {
//        try {
////            String parameters="af359e97cb424cd0a0c3409ae61c2baf";
////            String[] params = parameters.split(",");
//            List params = (List) parameters.get("params");
//            String contractId = String.valueOf(parameters.get("contractId"));
////            String[] params = {"af359e97cb424cd0a0c3409ae61c2baf"};
////            String contractId = "fe7da17113264ecfa640dd69b699667d";
//            for (int i = 0; i < params.size(); i++) {
//                params.set(i,"'"+params.get(i)+"'");
//            }
//            Object[] arr = params.toArray();
//            Map<String, Object> data = new HashMap<>();
//            Map map = fileWorkService.getDataById(contractId,"iyzlv_contract");
//            List<Map> sqlTexts = fileWorkService.getDataByParentId(contractId,"iyzlv_sqltext");
//            Map templateObj = fileWorkService.getDataById(map.get("templateId").toString(),"contract_template");
//            for (Map sqlText : sqlTexts) {
//                String sqlString = String.valueOf(sqlText.get("sqlString"));
//                String sql = MessageFormat.format(sqlString, arr);
//                Map mapSon = fileWorkService.getData(sql);
//                data.putAll(mapSon);
//            }
//            XWPFTemplate template = XWPFTemplate.compile(this.getClass().getClassLoader().getResource("").getPath() + templateObj.get("address").toString())
//                    .render(data);
//            OutputStream out;
//            response.reset();
//            response.addHeader("Access-Control-Allow-Origin", "*");
//            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
//            response.setContentType("application/force-download");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(String.valueOf(map.get("contractName"))+".docx","utf-8"));
//            response.setHeader("Access-Control-Expose-Headers", "FileName");
//            out= response.getOutputStream();
////             out = new FileOutputStream("D:\\下载\\二手车业务-最高额保证担保合同.docx");
//            template.write(out);
//            out.flush();
//            out.close();
//            template.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * 生成001的编号
     *
     * @param maxNum 最大数
     * @param count  累计的
     * @return
     */
    public static String sequenceCode(Long maxNum, Long count) {
        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 >= strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    }

    /**
     * 获取流程下对应得dealercode
     */
    public String dealercodelist(String instanceId,String dealerNameCN,String sector) {
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setInstanceId(instanceId);
        basicInformation.setDealerNameCN(dealerNameCN);
        List<BasicInformation> basicInformations = basicInformationService.selectBasicInformationList(basicInformation);
        if(StringUtils.isEmpty(basicInformations)){
            throw new BaseException("BasicInformation没对应得数据");
        }
        BasicInformation basicInformation1 = basicInformations.get(0);
        String sector1 = basicInformation1.getSector();
        String dealerCodeFromWFS = basicInformation1.getDealerCodeFromWFS();
        String[] split = sector1.split(",");
        String[] splits = dealerCodeFromWFS.split(",");
        String dealercode = "";
        for (int i = 0; i <split.length ; i++) {
            if(split[i].equals(sector)){
                for (int j = 0; j <splits.length ; j++) {
                    dealercode = splits[i];
                }
            }
        }
        return dealercode;
    }

    /**
     * 拼主合同号
     */
    public String maincontractno (String dealercode,String letter) {
        DealercodeCount dealercodeCount = new DealercodeCount();
        dealercodeCount.setDealercode(dealercode);
        dealercodeCount.setTemp(letter);
        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
        if(StringUtils.isEmpty(dealercodeCounts)){
            dealercodeCount.setTemp(letter);
            dealercodeCount.setCount((long) 1);
            dealercodeCountService.insertDealercodeCount(dealercodeCount);
        }

        //拼人民币循环贷款主合同号
        String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        String month = new SimpleDateFormat("M", Locale.CHINESE).format(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        try {
            month = new SimpleDateFormat("MMMMM", Locale.US).format((new SimpleDateFormat("MM")).parse(month));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DealercodeCount dealercodeCount1 = dealercodeCountService.selectDealercodeCountList(dealercodeCount).get(0);
        Long count = dealercodeCount1.getCount();
        String code = sequenceCode((long) 1000, count);
        //用完这个字段开始自增，并且自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
//        BeanUtil.copyProperties(dealercodeCount1,dealercodeCount);
//        if(count+1>999 || dateNowStr.equals("01-01")){
//            dealercodeCount.setCount((long)1);
//        }else {
//
//            dealercodeCount.setCount(count+1);
//        }
//        dealercodeCountService.updateDealercodeCount(dealercodeCount);
        //TODO 用变量
        String contrctcode = dealercode+letter+year+month+code;
        return contrctcode;
    }

    @PostMapping("/updatedealercodeCount")
    //合同下载页面走过后，修改dealercodeCount的count值，编号值在每次结束流程结束的时候自增
    public int updatedealercodeCount(){
        DealercodeCount dealercodeCount = new DealercodeCount();
        //查该表全部数据，然后把count编号全加一遍
        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        for (DealercodeCount dc : dealercodeCounts){
            //自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
            if(dc.getCount()+1>999 || dateNowStr.equals("01-01")){
                dc.setCount((long)1);
            }else {

                dc.setCount(dc.getCount()+1);
            }
            dealercodeCountService.updateDealercodeCount(dc);
        }
        return 1;
    }


}
